<template>
	<view class="header-container">
		<view class="header-section" :style="{ background: backGroundColor,height: totalHeight + 5 + 'px' }">
			<!-- 状态栏占位 -->
			<view class="status-bar" :style="{ height: statusBarHeight + 'px'}"></view>
			<!-- 顶部导航 -->
			<view class="nav-header" :style="{ height: navHeight + 'px' }">
				<view class="nav-content">
					<view class="back" @click="goBack" v-if="isShowBack">
						<uni-icons type="left" size="24" :color="fontColor"></uni-icons>
					</view>
					<text class="title" :style="{color: fontColor}">{{title}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "custom-header",
		props: {
			// 头部标题
			title: {
				type: String,
				default: ''
			},
			// 是否显示返回按钮
			isShowBack: {
				type: Boolean,
				default: true
			},
			// 字体颜色
			fontColor: {
				type: String,
				default: "#000"
			},
			// 背景颜色
			backGroundColor: {
				type: String,
				default: "#fff"
			},
			// 返回事件
			goBackFunc: {
				type: Function,
				default: function() {
					uni.navigateBack()
				}
			}
		},
		mounted() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight
			// 获取胶囊按钮位置信息
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			// 计算导航栏高度
			this.navHeight = (this.menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + this.menuButtonInfo.height
			// 总高度
			this.totalHeight = this.statusBarHeight + this.navHeight;
			// 将获取到的顶部高度传给父组件
			this.getScreenTopHeight();
		},
		methods: {
			getScreenTopHeight() {
				this.$emit('getScreenTopHeight',this.totalHeight);
			},
			goBack() {
				if (this.goBackFunc) {
					this.goBackFunc();
				} else {
					uni.navigateBack();
				}
			}
		},
		data() {
			return {
				totalHeight: 0,
				menuButtonInfo: null,
				statusBarHeight: 0,
				navHeight: 44, // 默认导航栏高度
			};
		}
	}
</script>

<style lang="scss">
	.header-container {
		position: sticky;
		z-index: 999;
		top: 0;
	}
	.header-section {
		padding-bottom: 20rpx;
		.nav-header {
			width: 100%;
			.nav-content {
				position: relative;
				display: flex;
				align-items: center;
				height: 100%;
				padding: 0 30rpx;
				.back {
					position: absolute;
					left: 30rpx;
					height: 100%;
					display: flex;
					align-items: center;
				}
				.title {
					flex: 1;
					text-align: center;
					font-size: 32rpx;
					font-weight: 500;
				}
			}
		}
	}
</style>